#!/usr/bin/perl

use IO::Socket;
use Getopt::Long;

my($is_client,$is_server,$ip,$port,$msg,$help);

$is_client = 0;
$is_server = 0;
$ip = "127.0.0.1";
$port = 1234;
$msg="hello\n";

my $res = GetOptions("ip=s" => \$ip,
										 "port=i" => \$port,
										 "msg=s" => \$msg,
										 "client" => \$is_client,
										 "server" => \$is_server,
										 "help" => \$help);
if($res != 1)
{
	&PrintUsage();
}

if($help)
{
	&PrintUsage();
}

if($is_client && $is_server)
{
	printf("can't be client and server\n");
	&PrintUsage();
}

if(!$is_client && !$is_server)
{
	printf("default is client\n");
	$is_client=1;
}

if($is_client)
{
	&Client();
	exit(0);
}

if($is_server)
{
	&Server();
	exit(0);
}
										 
sub PrintUsage()
{
	printf("\t%s ARGS [OPTIONS]...\n",$0);
	printf("\tARGS: -i ip -p port -m msg\n");
	printf("\t\t-i,--ip ip\n");
	printf("\t\t\tclient or server ip\n");
	printf("\t\t\tdefault is 127.0.0.1\n");
	printf("\t\t-p,--port port\n");
	printf("\t\t\tclient or server port\n");
	printf("\t\t\tdefault is 1234\n");
	printf("\t\t-m,--msg msg\n");
	printf("\t\t\tmsg to transfer\n");
	printf("\t\t\tdefault is hello\n");
	printf("\tOPTIONS: -c|-s -h\n");
	printf("\t\t-c,--client\n");
	printf("\t\t\tclient mode\n");
	printf("\t\t-s,--server\n");
	printf("\t\t\tserver mode\n");
	printf("\t\t-h,-help\n");
	printf("\t\t\tshow helps\n");
	
	exit(1);
}

sub Client()
{
	$client = IO::Socket::INET->new(PeerPort  => $port
																,PeerAddr => $ip
																,Timeout => 5
																,Proto     => "udp")
    or die "Couldn't be a udp client on port $server_port : $@\n";

	my $buff=$msg;
	print "send:$buff\n";
	$client->send($buff);
	$server=$client->recv($datagram,1024);
	if($server eq "")
	{
		print "test failed\n";
	}
	else
	{
		print "recv:$datagram\n";
		print "test ok\n"
	}
}

sub Server()
{
	$server = IO::Socket::INET->new(
																LocalAddr => $ip,
																LocalPort => $port,
                                Proto     => "udp")
    or die "Couldn't be a udp server on port $server_port : $@\n";

	my $buff;
	while ($him = $server->recv($datagram, 1024)) {
		printf("recv from: %s:%d\n",$server->peerhost(),$server->peerport());
    $server->send($datagram);
	}
}





